package demo.game.chess.common;

public class PiecePawn extends AbstractChessPiece {

	public PiecePawn(final ChessCell initialPosition) {
		super(initialPosition);
	}

	private ChessMove createPawnMove(final ChessBoard board,
			final ChessCell origin, final ChessCell target) {

		ChessMove move = new ChessMove(origin, target);
		if (target.getRow() == 0 || target.getRow() == 7) {
			move.setPawnPromotion(EnumChessPiece.queen);
		}
		return move;
	}

	@Override
	protected ChessMove createPieceSpecificMove(final ChessBoard board,
			final ChessCell origin, final ChessCell target)
			throws MoveException {
		int diffRow = target.getRow() - origin.getRow();
		int diffCol = target.getColumn() - origin.getColumn();

		if (Math.abs(diffRow) > 2) {
			return null;
		}

		if (getColor() == EnumChessColor.white && diffRow >= 0) {
			// for white player, the piece must move up (diffRow < 0)
			return null;
		} else if (getColor() == EnumChessColor.black && diffRow <= 0) {
			// for black player, the piece must move down (diffRow > 0)
			return null;
		}

		if (Math.abs(diffRow) == 2 && 0 != diffCol) {
			return null;
		}

		if (Math.abs(diffRow) == 2) {
			// check that the piece is in the initial position, and no obstacle.
			if (!getType().hasInitialPositionAt(origin)) {
				return null;
			}
			checkObstacle(board, origin, target);
		}

		AbstractChessPiece pieceAtTarget = board.getPieceAt(target);
		if (diffCol == 0 && null == pieceAtTarget) {
			return createPawnMove(board, origin, target);

		} else if (Math.abs(diffCol) == 1 && null != pieceAtTarget
				&& pieceAtTarget.getColor() != this.getColor()) {
			return createPawnMove(board, origin, target);

		}
		return null;
	}

	@Override
	public EnumChessPiece getType() {
		return EnumChessPiece.pawn;
	}

}
